package cn.rulian.car.outbill.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.rulian.base.auth.ann.Access;
import cn.rulian.base.auth.bo.Organ;
import cn.rulian.base.auth.bo.User;
import cn.rulian.base.common.dto.Message;
import cn.rulian.base.common.dto.UserInfo;
import cn.rulian.base.common.util.xx;
import cn.rulian.base.common.vo.Result;
import cn.rulian.car.outbill.bo.OutBill;
import cn.rulian.car.outbill.bo.OutBillFlow;
import cn.rulian.car.outbill.bo.UseOrgan;
import cn.rulian.car.outbill.dao.OutBillStateDao;
import cn.rulian.car.outbill.dao.UseOrganDao;
import cn.rulian.car.outbill.dto.Rate;
import cn.rulian.car.outbill.service.OutBillFlowService;
import cn.rulian.car.outbill.service.OutBillService;
import cn.rulian.car.outbill.vo.OutBillVo;

/**
 * 车辆外出单--申请
 */

@Access(authCode="outBillApply")
@Controller
@RequestMapping("/car/outbill/outBillApply")
public class OutBillApplyController {
	
	@Autowired
	private OutBillService service;

	@Autowired
	private OutBillStateDao outBillStateDao;
	
	@Autowired
	private UseOrganDao useOrganDao;
	
	@Autowired
	private OutBillFlowService outBillFlowService; 
	
	//private final Logger log = LoggerFactory.getLogger(getClass());
	
	private final String path="car/outbill/outbillApply_"; //页面基本路径

	/**
	 * 页面基本路径
	 */
	private String getPath()
	{
		return path;
	}
	
	
	/**
	 * 列表页面
	 */
	@RequestMapping("/listPage")
	public String listPage() {
		return this.getPath()+"list";
	}

	/**
	 * 查询
	 */
	@RequestMapping("/listData")
	@ResponseBody
	public Result listData(HttpSession session,OutBillVo vo) {
		//取当前用户
		UserInfo userInfo = UserInfo.getUserInfo(session); 
		User user = userInfo.getUser();
		return service.queryApply(vo,user.getId());
	}

	/**
	 * 增加页面
	 */
	@RequestMapping("/addPage")
	public String addPage(Model model) {
		Rate rate = service.getRate(); //费率
		model.addAttribute("rate",rate);
		return this.getPath()+"add";
	}

	/**
	 * 增加
	 */
	@RequestMapping("/add")
	@ResponseBody
	public Message add(HttpSession session, OutBillVo vo) {
		
		//取当前用户
		UserInfo userInfo = UserInfo.getUserInfo(session); 
		User user = userInfo.getUser();
		
		//设置默认值
		OutBill bo = vo.getObj();
		bo.setAddTime(new Date()); //增加时间
		bo.setDataSource(OutBill.DATASOURCE_APPLE);//数据来源（申请）
		bo.setApplyUserId(user.getId()); //申请用户ID
		bo.setApplyUserName(user.getName()); //申请用户姓名
		bo.setOpeTimeNear(new Date()); //最近操作时间
		bo.setOrgan(this.getOrgan(user)); //用车部门
		bo.setState(outBillStateDao.findFirstByCode("01")); //状态：草稿
		
		OutBillFlow flow = new OutBillFlow();
		flow.setOutBill(bo);
		flow.setOpe("创建");
		flow.setOpeUserName(user.getName());
		flow.setOpeTime(new Date());
		
		Message rm = new Message();
		try {
			service.save(bo);
			outBillFlowService.save(flow);
			
			rm.setMsg("保存成功！");
			rm.setCode(Message._SUCCESS);
		} catch (Exception e) {
			rm.setMsg("保存失败，异常信息：<br/>" + e.toString());
			rm.setCode(Message._ERROR);
			e.printStackTrace();
		}
		return rm;
	}
	
	/**
	 * 根据当前用户信息，获取单据的“部门”
	 */
	private UseOrgan getOrgan(User user)
	{
		Organ organ = user.getOrgan();
		if(organ==null)
		{
			return null;
		}
		String organCode = organ.getAllCode(); //当前用户的机构编码
		
		List<UseOrgan> list = useOrganDao.findAll();
		for(UseOrgan type:list)
		{
			String code = type.getStr3(); //部门编码
			if(xx.isEmpty(code))
			{
				continue;
			}
			if(organCode.startsWith(code))
			{
				return type;
			}
		}
		return null;
	}

	/**
	 * 修改页面
	 */
	@RequestMapping("/updatePage")
	public String updatePage(Model model, Long id) {
		model.addAttribute("bo", service.findOne(id));
		return this.getPath()+"update";
	}

	/**
	 * 修改
	 */
	@RequestMapping("/update")
	@ResponseBody
	public Message update(OutBillVo vo,Long id) {
		Message rm = new Message();
		try {
			OutBill obj = vo.getObj();
			OutBill bo = service.findOne(id);
			bo.setUser(obj.getUser());
			bo.setDestination(obj.getDestination());
			bo.setBeginTime(obj.getBeginTime());
			bo.setRemark(obj.getRemark());
			service.save(bo);
			
			rm.setMsg("保存成功！");
			rm.setCode(Message._SUCCESS);
		} catch (Exception e) {
			rm.setMsg("保存失败，异常信息：<br/>" + e.toString());
			rm.setCode(Message._ERROR);
			e.printStackTrace();
		}
		return rm;
	}

	/**
	 * 删除
	 */
	@RequestMapping("/delete")
	@ResponseBody
	public Message delete(Long ids[]) {
		Message rm = new Message();
		try {
			for(Long id:ids)
			{
				List<OutBillFlow> ls = outBillFlowService.findByOutBill_id(id);
				outBillFlowService.delete(ls); //删除流转
				service.delete(id);
			}
			
			rm.setMsg("删除成功！");
			rm.setCode(Message._SUCCESS);
		} catch (Exception e) {
			rm.setMsg("删除失败，异常信息：<br/>" + e.toString());
			rm.setCode(Message._ERROR);
			e.printStackTrace();
		}
		return rm;
	}
	
	/**
	 * 提交单据
	 */
	@RequestMapping("/submitBill")
	@ResponseBody
	public Message submitBill(HttpSession session,Long id) {
		Message rm = new Message();
		try {
			OutBill bo = service.findOne(id);
			bo.setState(outBillStateDao.findFirstByCode("02")); //状态：待审核
			bo.setOpeTimeNear(new Date());
			service.save(bo);

			//取当前用户
			UserInfo userInfo = UserInfo.getUserInfo(session); 
			User user = userInfo.getUser();
			//保存流转
			OutBillFlow flow = new OutBillFlow();
			flow.setOutBill(bo);
			flow.setOpe("提交");
			flow.setOpeUserName(user.getName());
			flow.setOpeTime(new Date());
			outBillFlowService.save(flow);
			
			rm.setMsg("提交成功！");
			rm.setCode(Message._SUCCESS);
		} catch (Exception e) {
			rm.setMsg("提交失败，异常信息：<br/>" + e.toString());
			rm.setCode(Message._ERROR);
			e.printStackTrace();
		}
		return rm;
	}
	
	/**
	 * 详情页面
	 */
	@RequestMapping("/detailPage")
	public String detailPage(Model model, Long id) {
		model.addAttribute("bo", service.findOne(id));
		return this.getPath()+"detail";
	}

	
}
